<?php

class UserController extends Controller {

    public function actionTaskuser() {
        $this->pageTitle = Yii::t('app', 'List task by user').'';
        $model = new Task();

        if(isset($_GET['Task'])) {
            $model->unsetAttributes();
            $model->attributes=$_GET['Task'];
        }

        $this->render('taskuser', array(
            'model' => $model,
        ));
    }

    public function actionTaskdetail($id = null) {
        $this->pageTitle = Yii::t('app', 'Task detail');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('user/taskuser'));
        }

        //Get user
        $model = Task::model()->findByPk($id, 'del_flg = 0');

        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('user/taskuser'));
        }

        if($model->responsible != Yii::app()->user->getState('username'))
            $this->redirect(array('user/taskuser'));

        //update status in analyst
        if (isset($_POST['status']) && isset($_POST['ids'])) {
            if($_POST['status'] && $_POST['ids']){
                $stt = $_POST['status'];
                $arrIds = $_POST['ids'];
                $transaction = Yii::app()->db->beginTransaction();
                try {
                    $errors = array();
                    $errorMessages = '';
                    $mailStatus =  array();

                    $i=0;
                    foreach($arrIds as $id){
                        $modelTaskAnalyst = TaskAnalyst::model()->findByPk($id, 'del_flg = 0');
                        if($modelTaskAnalyst->status!=Constant::STATUS_CLOSE){
                            $modelTaskAnalyst->status = $stt;
                            if (!$modelTaskAnalyst->save()) {
                                $errors[] = $modelTaskAnalyst->getErrors();
                            }else{
                                $mailStatus[$i]['stt'] = $stt;
                                $mailStatus[$i]['step'] = $modelTaskAnalyst->step_analyst;
                                $i++;
                            }
                        }
                    }

                    //Process error message
                    if ($errors) {
                        foreach ($errors as $k => $v) {
                            foreach ($v as $f) {
                                foreach ($f as $id => $m) {
                                    $errorMessages .= $m.'<br>';
                                }
                            }
                        }
                    }

                    if (!empty($errorMessages)) throw new Exception();
                    $transaction->commit();

                    Yii::app()->user->setFlash('success', Yii::t('app', 'Update status process analyst in task successful!'));

                    if(!empty($mailStatus)){
                        //send mail  change status to admin
                        $sub = Yii::t('app', 'Status step analyst in task is update');
                        $content = Yii::t('app', 'Hi Admin!').'<br>';
                        $content .= Yii::t('app', 'Analyster update status step analyst in task: ').'<br>';
                        foreach($mailStatus as $value){
                            $content .= '<i>'.$value['step']. ' : </i><b>'. Constant::getStatus($value['stt']).'</b><br>';
                        }
                        Common::sentMail(Yii::app()->params['adminEmail'], $sub, $content);
                    }

                } catch (Exception $e) {
                    $transaction->rollback();
                    Yii::app()->user->setFlash('error', "$errorMessages");
                }
            }else{
                    Yii::app()->user->setFlash('error', Yii::t('app', 'Please check step process analyst or choose status!'));
            }
        }

        $data = array();
        $data['attribute_matter'] = $model->attribute_matter->name;
        $data['content_matter'] = $model->attribute_matter->note;
        $data['deadline'] = $model->deadline;
        $data['delivery_date'] = $model->delivery_date;
        $data['status'] = Constant::getStatus($model->status);

        $this->render('taskdetail', array(
            'modelTaskAnalyst' => new TaskAnalyst(),
            'model' => $model,
            'data' => $data
        ));
    }

    public function actionUpdatestatus($id = null){
        $this->pageTitle = Yii::t('app', 'Update status task');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('user/taskuser'));
        }

        $model = Task::model()->findByPk($id, 'del_flg = 0');

        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('user/taskuser'));
        }

        if($model->responsible != Yii::app()->user->getId())
            $this->redirect(array('user/taskuser'));

        if (isset($_POST['Task']) && $data = $_POST['Task']) {
            $model->attributes = $data;
            if ($model->save()) {
                // send mail to admin
                $sub = Yii::t('app', 'Status task update');
                $content = Yii::t('app', 'Hi Admin!').'<br>';
                $content .= Yii::t('app', 'Analyster update status task to ').'<b>'.Constant::getStatus($model->status).'</b>';
                Common::sentMail(Yii::app()->params['adminEmail'], $sub, $content);

                Yii::app()->user->setFlash('success', Yii::t('app', 'Status updated success!'));
                $this->redirect(array('user/taskuser'));
            }
        }

        $this->render('updatestatus', array('model' => $model));
    }

    public function actionStepstatus($id = null){
        $this->pageTitle = Yii::t('app', 'Update status step analyst');
        $id_task = isset($_GET['t']) ? $_GET['t'] : 0;
        if (!$id || !$id_task) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(array('user/taskuser'));
        }

        $model = TaskAnalyst::model()->findByPk($id, 'del_flg = 0 AND id_task = '.$id_task);

        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(array('user/taskuser'));
        }

        if($model->status == Constant::STATUS_CLOSE){
            $this->redirect(array('user/taskdetail', array('id'=>$model->id_task)));
        }

        if (isset($_POST['TaskAnalyst']) && $data = $_POST['TaskAnalyst']) {
            $model->attributes = $data;
            if ($model->save()) {

                Yii::app()->user->setFlash('success', Yii::t('app', 'Status step analyst updated success!'));
                $this->redirect(array('user/taskuser'));
            }
        }

        $this->render('stepstatus', array('model' => $model));
    }

    public function actionInfo(){
        $this->pageTitle = Yii::t('app', 'Account Infomation');
        $id = Yii::app()->user->getId();
        //Get user
        $model = Admin::model()->findByPk($id, 'del_flg = 0');

        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }
        //process change password
        if (isset($_POST['Admin']['password']) && $_POST['Admin']['password']!='') {
            $model->password = $_POST['Admin']['password'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('app', 'Change password success!'));
            }
        }
        $model->password='';
        $this->render('info', array('model' => $model));
    }

/*====================== Manager in admin page =======================*/
    public function actionIndex() {
        $this->pageTitle = Yii::t('app', 'Manager user');

        $model = new Admin();

        $this->render('index', array(
            'model' => $model,
        ));
    }

    public function actionAdd() {
        $this->pageTitle = Yii::t('app', 'Manager user');

        $model = new Admin();

        if (isset($_POST['Admin']) && $data = $_POST['Admin']) {
            $model->attributes = $data;
//            $model->password = Admin::encrypt($data['password']);
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('app', 'User created success!'));
                $this->redirect(array('user/index'));
            }
        }

        $this->render('add', array('model' => $model));
    }

    public function actionView($id = null) {
        $this->pageTitle = Yii::t('app', 'Manager user');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }

        //Get user
        $model = Admin::model()->findByPk($id, 'del_flg = 0');

        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }
        //process change password
        if (isset($_POST['Admin']['password']) && $_POST['Admin']['password']!='') {
            $model->password = $_POST['Admin']['password'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('app', 'User change password success!'));
                $this->redirect(array('user/index'));
            }
        }

        $model->password='';
        $this->render('view', array('model' => $model));
    }

    public function actionUpdate($id = null) {
        $this->pageTitle = Yii::t('app', 'Manager user');
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }

        //Get Admin
        $model = Admin::model()->findByPk($id, 'del_flg = 0');

        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }

        if (isset($_POST['Admin']) && $data = $_POST['Admin']) {
            $model->attributes = $data;
            if ($model->save()) {
                Yii::app()->user->setFlash('success', Yii::t('app', 'User updated success!'));
                $this->redirect(array('user/index'));
            }
        }
        $this->render('update', array('model' => $model));
    }

    public function actionDelete($id = null) {
        if (!$id) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Missing parameters!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }

        //Get Admin by id
        $model = Admin::model()->findByPk($id, 'del_flg = 0');

        if (!$model) {
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }
        if($model->id_profile==Constant::ROLE_ANALYST){
            $model->del_flg = 1;
            if ($model->save(false)) {
                if(!isset($_GET['ajax'])){
                    Yii::app()->user->setFlash('success', Yii::t('app', 'User - Deleted Successfully'));
                    $this->redirect(array('analysis/index'));
                }
                else{
                    echo '<div class="alert alert-success fade in"><button type="button" class="close" data-dismiss="alert">×</button>'.Yii::t('app', 'User - Deleted Successfully').'</div>';
                    die();
                }

            }
        }else{
            Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid record!'));
            $this->redirect(Yii::app()->request->urlReferrer);
        }

    }

}